package com.lau.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author:Lau
 * @create: 2024-01-19 15:18
 * @Description: Spring工具类
 */
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    /**
     * 获取对象
     *
     * @param name bean对象名称
     * @return Object 一个以所给名字注册的bean的实例
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) applicationContext.getBean(name);
    }

    /**
     * 获取类型为requiredType的对象
     *
     * @param requiredType bean类型
     * @return bean实例
     *
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<?> requiredType) {
         T result = (T) applicationContext.getBean(requiredType);
        return result;
    }

}
